package cn.tiger.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RunnableDemo {

    public static void main(String[] args) {

        //使用线程池方式运行runnable
        ExecutorService executor = Executors.newFixedThreadPool(4);
        executor.execute(new MyRunnable("ExecutorService方式运行runnable"));
        // 关闭线程池
        executor.shutdown();


        //使用Thread方式运行runnable
        new Thread(new MyRunnable("Thread方式运行runnable")).start();

//        执行结果
//        pool-1-thread-1 开始执行 ExecutorService方式运行runnable
//        pool-1-thread-1 MyRunnable 实现 Runnable接口 ExecutorService方式运行runnable
//        pool-1-thread-1 完成 ExecutorService方式运行runnable

//        Thread-0 开始执行 Thread方式运行runnable
//        Thread-0 MyRunnable 实现 Runnable接口 Thread方式运行runnable
//        Thread-0 完成 Thread方式运行runnable

    }

    // 自定义Runnable实现
    static class MyRunnable implements Runnable {
        private final String name;

        public MyRunnable(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " 开始执行 " + name);
                // 模拟任务执行时间
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + " MyRunnable 实现 Runnable接口 " + name);
                System.out.println(Thread.currentThread().getName() + " 完成 " + name);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
